package com.qfedu.openplateform.gateway.filter;

import com.qfedu.openplateform.common.entity.LoggerBean;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @author lileijian
 * @create 2021-12-05 0:48
 */
@Component
public class LoggerFilter implements HandlerInterceptor {

    private ThreadLocal<Date> startDate = new ThreadLocal<>();
    private ThreadLocal<Long> startTime = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 请求开始之前时间
        startDate.set(new Date());
        startTime.set(System.currentTimeMillis());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        LoggerBean loggerBean = new LoggerBean();

        //总时长
        loggerBean.setTotalTime(System.currentTimeMillis() - startTime.get());

        loggerBean.setReveivceTime(startDate.get());
        loggerBean.setResponseTime(new Date());

        loggerBean.setApiName(request.getParameter("method_name"));
        loggerBean.setApp_key(request.getParameter("app_key"));

        loggerBean.setContent(request.getParameterMap().toString());
        loggerBean.setServerIp(request.getServerName());
        loggerBean.setRemoteIp(request.getRemoteAddr());

        System.out.println("-----------loggerBean---------------" + loggerBean);

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
